/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fr.uha.ensisa.kfetmanager.product;

import java.util.Iterator;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.validation.ValidationException;

/**
 *
 * @author JC
 */
@Stateless
public class ProductManagerBean implements ProductManagerRemote {
    @PersistenceContext(unitName="kfet-manager-ejbPU")
    private EntityManager em;

    @Override
    public Product createProduct(Product product, String name, double price, String imageUrl) {
        if (product == null) throw new ValidationException("L'objet product est null");
        if (name == null || name.equals("")) throw new ValidationException("L'objet name est null ou vide");

        product.setName(name);
        product.setPrice(price);
        product.setImageUrl(imageUrl);

        em.persist(product);
        return product;
    }

    @Override
    public Product updateProduct(Product product, String name, double price, String imageUrl) {
        if (product == null) throw new ValidationException("L'objet product est null");
        if (name == null || name.equals("")) throw new ValidationException("L'objet name est null ou vide");

        product.setName(name);
        product.setPrice(price);
        product.setImageUrl(imageUrl);

        em.merge(product);
        return product;
    }

    @Override
    public Product getProduct(Long id) {
        if (id == null) throw new ValidationException("L'objet ID est null");
        try {
            return (Product)em.find(Product.class, id);
        } catch(Exception e) {
            return null;
        }
    }

    @Override
    public List<Product> getProducts() {
        Query query = em.createQuery("SELECT p FROM Product p");
        List<Product> products = query.getResultList();

        return products;
    }

    @Override
    public Iterator<Product> iterator() {
        return this.getProducts().iterator();
    }

    @Override
    public void deleteProduct(Product product) {
        if (product == null) throw new ValidationException("L'objet product est null");

        em.remove(em.merge(product));
    }

}
